package com.example.spark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spark.dao.BackgroundDao;
import com.example.spark.entity.Background;
import com.example.spark.entity.result.CommonResult;
import com.example.spark.service.BackgroundService;
import com.example.spark.service.minio.MinioCloudStorageService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class BackgroundServiceImpl extends ServiceImpl<BackgroundDao, Background> implements BackgroundService {

    @Autowired
    private BackgroundDao backgroundDao;

    @Resource
    MinioCloudStorageService minIoService;

    public CommonResult insertBackground(@RequestParam MultipartFile file) throws Exception {
        // 根据id查询到真实姓名作为简历的文件名
        String name = "background";
        // getOriginalFileName方法获取的是文件的完整名称，包括文件名称+文件拓展名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //后缀
        // 上传文件并获取文件存储路径
        String photoUrl = minIoService.uploadPhotoSuffix(file.getBytes(), extension, name);
        Background background = new Background();
        background.setPhoto(photoUrl);
        int insert = backgroundDao.insert(background);
        CommonResult commonResult = new CommonResult(200, "success", insert);
        return commonResult;
    }

    public CommonResult updateBackground(MultipartFile file, Long id) throws Exception {
        if (file != null) {
            // 根据id查询到真实姓名作为简历的文件名
            String name = "background";
            // getOriginalFileName方法获取的是文件的完整名称，包括文件名称+文件拓展名
            String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //后缀
            // 上传文件并获取文件存储路径
            String photoUrl = minIoService.uploadPhotoSuffix(file.getBytes(), extension, name);
            Background background = new Background();
            background.setId(id);
            background.setPhoto(photoUrl);
            int result = backgroundDao.updateById(background);
            CommonResult commonResult = new CommonResult(200, "success", result);
            return commonResult;
        } else {
            CommonResult commonResult = new CommonResult(200, "success", "未正确传输图片");
            return commonResult;
        }
    }

    public CommonResult selectBackground() {
        Background background = backgroundDao.selectOne(null);
        CommonResult commonResult = new CommonResult(200, "success", background);
        return commonResult;
    }

}
